package me.zhengjie.tool;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

public class WeekDateUtils {

    private static final DateTimeFormatter YYYYMMDD_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");

    /**
     * 获取指定日期所在周的星期一到星期日日期(yyyymmdd格式)
     * 自动处理跨月、跨年情况
     */
    public static List<String> getWeekDates(LocalDate date) {
        LocalDate monday = getMondayOfWeek(date);
        List<String> weekDates = new ArrayList<>();

        for (int i = 0; i < 7; i++) {
            LocalDate currentDate = monday.plusDays(i);
            weekDates.add(currentDate.format(YYYYMMDD_FORMATTER));
        }
        return weekDates;
    }

    /**
     * 获取当前周的星期一到星期日日期(yyyymmdd格式)
     */
    public static List<String> getCurrentWeekDates() {
        return getWeekDates(LocalDate.now());
    }

    /**
     * 获取指定日期所在周的星期一日期
     */
    public static LocalDate getMondayOfWeek(LocalDate date) {
        return date.with(DayOfWeek.MONDAY);
    }

    /**
     * 获取指定日期所在周的星期日日期
     */
    public static LocalDate getSundayOfWeek(LocalDate date) {
        return date.with(DayOfWeek.SUNDAY);
    }

    /**
     * 获取周日期范围描述
     */
    public static String getWeekRangeDescription(LocalDate date) {
        LocalDate monday = getMondayOfWeek(date);
        LocalDate sunday = getSundayOfWeek(date);

        // 判断是否跨年
        if (monday.getYear() != sunday.getYear()) {
            return monday.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日")) +
                    " - " +
                    sunday.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日"));
        }
        // 判断是否跨月
        else if (monday.getMonth() != sunday.getMonth()) {
            return monday.format(DateTimeFormatter.ofPattern("MM月dd日")) +
                    " - " +
                    sunday.format(DateTimeFormatter.ofPattern("MM月dd日")) +
                    " (" + monday.getYear() + "年)";
        }
        // 同月
        else {
            return monday.getMonthValue() + "月" + monday.getDayOfMonth() + "日" +
                    " - " +
                    sunday.getDayOfMonth() + "日" +
                    " (" + monday.getYear() + "年)";
        }
    }
}
